package com.yiwei.zxp;

import android.*;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.Const;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.HomePagerEvent;
import com.yiwei.zxp.event.MsgTotalEvent;
import com.yiwei.zxp.event.UserInfoRequestEvent;
import com.yiwei.zxp.fragment.BussinessMyFragment;
import com.yiwei.zxp.fragment.BuyerMyFragment;
import com.yiwei.zxp.fragment.MainCenterFragment;
import com.yiwei.zxp.fragment.MainPacketFragment;
import com.yiwei.zxp.fragment.MyShareMoneyFragment;
import com.yiwei.zxp.fragment.ShopCartFragment;
import com.yiwei.zxp.fragment.ShopMallFragment;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.DownloadUtil;
import com.yiwei.zxp.util.FileUtils;
import com.yiwei.zxp.util.FragmentUtils;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.PreferenceUtils;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.BussinessBottomLayout;
import com.yiwei.zxp.view.HomeViewPager;
import com.yiwei.zxp.view.SuperViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BussinessMainActivity extends BaseActivity implements BussinessBottomLayout.OnChooseListener {


    @BindView(R.id.pager)
    SuperViewPager pager;
    @BindView(R.id.bottom_menu)
    BussinessBottomLayout bottomMenu;
    //    @BindView(R.id.container)
//    FrameLayout container;
    private Fragment[] mFragments = new Fragment[6];
    private Unbinder unbiner;
    private DownloadBroadcastReceiver receiver;
    private DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    private MaterialDialog materialDialog;
    private long lastDownloadId = 0;
    private boolean isShowDialog = false;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    private int curIndex;
    public int isBussiness = 0;

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
//        outState.putInt("curIndex", curIndex);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bussiness_main);
        initBarTouming();
        unbiner = ButterKnife.bind(this);
//        if (savedInstanceState != null) {
//            curIndex = savedInstanceState.getInt("curIndex");
//        }
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        mFragments[0] = new ShopMallFragment();
        mFragments[1] = new MainPacketFragment();
        mFragments[2] = new ShopCartFragment();
        mFragments[3] = new BuyerMyFragment();
        mFragments[4] = new BussinessMyFragment();
        mFragments[5] = new MainCenterFragment();

//        FragmentUtils.add(getSupportFragmentManager(), mFragments, R.id.container, curIndex);
//        Fragment[] fragments = new Fragment[]{new BuyerMyFragment(), new BussinessMyFragment()};
        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {

                return mFragments[position];
            }

            @Override
            public int getCount() {
                return mFragments.length;
            }

        });
        pager.setOffscreenPageLimit(3);
        bottomMenu.setOnChooseListener(this);
    }

    @Override
    public void onClick(int poi) {
        switch (poi) {
            case 0:
                pager.setCurrentItem(0);
                break;
            case 1:
                pager.setCurrentItem(1);
                break;
            case 2:
                pager.setCurrentItem(2);
                break;
            case 3:
                if (isBussiness == 0) {
                    pager.setCurrentItem(3);
                } else {
                    pager.setCurrentItem(4);
                }
                break;
        }
    }

    @Override
    public void onCenterClick() {
        pager.setCurrentItem(5);
    }

    public void changePage(int page) {
        isBussiness = page;
        if (page == 0) {
            pager.setCurrentItem(3);
        } else if (page == 1) {
            pager.setCurrentItem(4);
        }
//        pager.setCurrentItem(page);
//        FragmentUtils.showHide(curIndex = page, mFragments);
    }

    private static long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this,
                        "再按一次退出",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                this.finish();
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(HomePagerEvent event) {
        if (event.page == 0) {
            bottomMenu.selectPageOne();
        } else if (event.page == 2) {
            bottomMenu.selectPageFour();
        } else if (event.page == 1) {
            bottomMenu.selectPageTwo();
        }
//        pager.setCurrentItem(event.page);
    }

    public void setFragmentChange(int page) {
        if (page == 1) {
            bottomMenu.selectPageTwo();
        } else if (page == 0) {
            bottomMenu.selectPageOne();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
        EventBus.getDefault().unregister(this);
    }


    /**
     * 检查版本
     */
    public void checkUpdate() {
        FileUtils.delFile(Const.APP_NAME); //删除安装包

        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String url = PreferenceUtils.getString(this, "download_url", "");


        if (TextUtils.isEmpty(version) || TextUtils.isEmpty(url))
            return;

        try {
            String versionName = Util.getVersion(this);
            versionName = versionName.replace("", "");

            String versionNew = version.replace("", "");

            if (compareVersion(versionNew, versionName) > 0) {
//                isFirstTips = false;

                //注册下载监听
                receiver = new DownloadBroadcastReceiver();
                registerReceiver(receiver, new IntentFilter(
                        DownloadManager.ACTION_DOWNLOAD_COMPLETE));

                showInstallDialog();
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    private boolean canDownloadState() {
        try {
            int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private void showInstallDialog() {
        if (!isShowDialog) {
            isShowDialog = true;
            String updateContent = PreferenceUtils.getString(this, "upgrade_msg", "");
            if (updateContent.contains("{current_version}"))
                updateContent = updateContent.replace("{current_version}", Util.getVersion(this));
            if (updateContent.contains("{lastest_version}"))
                updateContent = updateContent.replace("{lastest_version}", PreferenceUtils.getString(this, "lastest_version", "1.0.0"));
            if (!Util.isWifi(this))
                updateContent = updateContent + ",\n当前网络不在WiFi环境，是否升级？";


//            String leftBtn;
//            if (PreferenceUtils.getInt(this, "forced_upgrade", 0) == 1)
//                leftBtn = "";
//            else leftBtn = "跳过";
            boolean isForce = true;
            if (PreferenceUtils.getInt(this, "forced_upgrade", 1) == 1)
                isForce = true;
            else isForce = false;
            Dialog.showVersionDialog(this, updateContent, isForce, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    isShowDialog = false;
                    if (!canDownloadState()) {
                        Dialog.showDefaultDialog(BussinessMainActivity.this, "提示", "请开启下载服务权限", getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                String packageName = "com.android.providers.downloads";
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + packageName));
                                startActivity(intent);
                            }

                            @Override
                            public void cancel() {
                                showInstallDialog();
                            }
                        });
                        return;
                    }
                    downloadApp();
                }

                @Override
                public void cancel() {

                }
            });

        }
    }


    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 初始化下载
     */
    private void initDownloadManager() {
        String url = PreferenceUtils.getString(this, "download_url", "");
        if (TextUtils.isEmpty(url)) return;

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(this)
                    .title("版本升级")
                    .content("正在下载安装包，请稍候..")
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
            request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, Const.APP_NAME);
//            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription(getResources().getString(R.string.app_name)
                    + "正在下载安装包，请稍候..");

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(this, "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null);
            getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }


    //用于显示下载进度
    private class DownloadChangeObserver extends ContentObserver {

        private DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
//                    materialDialog.dismiss();
                }
            }
        }


    }

    private int p = 10;

    /**
     * 下载广播
     */
    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            try {
                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                    long myDwonloadID = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                    long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                    if (refernece == myDwonloadID) {
                        manager = (DownloadManager) context
                                .getSystemService(DOWNLOAD_SERVICE);

//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                        else
                        DownloadUtil.installApp(BussinessMainActivity.this, myDwonloadID);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取权限回调 兼容6.0
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                initDownloadManager();
            } else {
                // 获取权限失败
                ToastUtil.makeText(this, "获取权限失败~");
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (materialDialog != null && materialDialog.isShowing()) {
//            isFirstTips = false;
            return;
        }
        checkUpdate();
        if (!isNeedUpdate()) {
            if (UserInfoGlobal.isLogin()) {
                getMsgTotal();
            }
            getUser();
        }
    }

    public void getMsgTotal() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        Api.api_service.getMessageCenter().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new MsgTotalEvent(result.datas.totalCount));
                });
    }

    public void getUser() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        Api.api_service.getUserInfo().compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        EventBus.getDefault().post(new UserInfoRequestEvent(true, result.datas));
                    } else {
                        EventBus.getDefault().post(new UserInfoRequestEvent(false, null));
                    }
                });
    }


    private boolean isNeedUpdate() {
        String versionName = Util.getVersion(this);
        versionName = versionName.replace("", "");
        String version = PreferenceUtils.getString(this, "lastest_version", "1.0.0");
        String versionNew = version.replace("", "");

        if (compareVersion(versionNew, versionName) > 0) {
            return true;
        } else {
            return false;
        }
    }
}
